import re
import openpyxl
from openpyxl import Workbook
import os
import requests
def parse_failure_message_regex(message):
    # 定义正则表达式
    pattern = re.compile(r"事件验证失败。关键词为(.*?),事件名为(.*?),期望结果为(.*?),实际结果为(.*?),查询模式为(.*?)$")

    # 使用正则表达式搜索字符串
    match = pattern.search(message)

    if match:
        return {
            "keyword": match.group(1),
            "event_name": match.group(2),
            "expected_result": match.group(3),
            "actual_result": match.group(4),
            "search_mode": match.group(5),
        }
    else:
        return None  # 如果没有找到匹配项，则返回None

def get_case_name(message):
# 正则表达式匹配用例名字和日志文件名


    pattern = re.compile(r"\[(.*?)\.py-->line")
    match = pattern.search(message)
    if match:
        case_name = re.search(pattern, message).group(1)
    else:
        return None, None
# 第二个正则表达式匹配日志文件名
    pattern_log = re.compile(r"本次采集的5D日志文件名为 (.*?)$")
    match = pattern_log.search(message)
    if match:
        log_file_name = re.search(pattern_log, message).group(1)
    else:
        return None, None
    return case_name,log_file_name
def solve_log(log_file):
    result=[]
    event_name_list={}

    # 用于存储结果的字典

    # 正则表达式，用于匹配测试用例名和事件名

    with open(log_file, 'r', encoding='utf-8') as file:
        for line in file:
            if not line:
                continue
            # 查找匹配的行
            case_name, log_file_name=get_case_name(line)
            if case_name:
                # print(case_name)
                # print(log_file_name)
                case_list = [case_name, log_file_name]
                continue
            error_message=parse_failure_message_regex(line)
            if error_message:
                case_name, log_file_name=case_list
                keyword= error_message["keyword"]
                event_name = error_message["event_name"]
                expected_result= error_message["expected_result"]
                actual_result = error_message["actual_result"]
                search_mode = error_message["search_mode"]

                message=[case_name, log_file_name,keyword,event_name,expected_result,actual_result,search_mode]
                if message not in result:
                    if event_name not in event_name_list.keys():
                        event_name_list[event_name]=1
                    else:
                        event_name_list[event_name]=event_name_list[event_name]+1
                    print([case_name, log_file_name])
                    print([keyword, event_name, expected_result, actual_result, search_mode])
                    result.append(message)
    file.close()
    # 创建一个Workbook对象
    wb = Workbook()
    # 激活默认的工作表
    ws = wb.active
    ws.append(["测试用例名字","日志名字","查找事件内容","查找事件名字","期望结果","实际结果","查询模式"])
    all = []
    for row in result:
        # row_values是当前行的数据列表
        row_values = row
        # 将数据写入到当前行，注意openpyxl的行索引从1开始
        ws.append(row_values)
        all.append([row[0][:8],row[3],(row[2].split(":"))[0],row[4],row[5],row[6]])
    ws.append([ "查找事件名字", "个数"])
    all.append([ "查找事件名字", "个数"])
    for row in event_name_list.keys():
        ws.append([row,event_name_list[row]])
        all.append([row,event_name_list[row]])
        # 保存文件
    wb.save("users.xlsx")
    return all
def get_result():
    log_list = os.listdir("Outputs/Logs")
    logfile=os.path.join("Outputs/Logs",log_list[-1])

    all=solve_log(logfile)
    return all
# get_result()
def list_to_markdown(data, headers=None):
    """
    将二维数据列表转换为Markdown表格。

    :param data: 二维数据列表
    :param headers: 可选，表格的列标题
    :return: Markdown格式的表格字符串
    """
    markdown = ""

    # 添加表头
    if headers:
        markdown += "| " + " | ".join(headers) + " |\n"
        markdown += "| " + " | ".join(['---'] * len(headers)) + " |\n"

    # 添加数据行
    for row in data:
        markdown += "| " + " | ".join(map(str, row)) + " |\n"

    return markdown
def send_dingding():
    headers = ["测试用例名字","事件名字","事件内容","期望结果","实际结果","查询模式"]
    data=get_result()
    # 生成Markdown表格
    markdown = list_to_markdown(data, headers)

    url = "https://oapi.dingtalk.com/robot/send?access_token=56666553b64d1b522c708287c48b408effbff881813fa0702e8192a0933ec1ad"
    # url= 'https://oapi.dingtalk.com/robot/send?access_token=bfb9aa2aabb8c9fd74d4353c65db4b676a3371073a46fe353efb3cbdc78ee372'

    message = {
        "at": {"atMobiles": ["15059946916"],
               "atUserIds": ["user123"],
               "isAtAll": False},
        "markdown": {
            "text": markdown,
            "title": "问题用例列表"
        },
        "msgtype": "markdown"
    }

    data = requests.post(url, json=message)
    print(data.json())
if __name__ == "__main__":
    # send_dingding()
    get_result()